import 'dart:convert';
import 'dart:io';

import 'package:app/common/colors.dart';
import 'package:app/components/bottom_enter_page.dart';
import 'package:app/utils/uint.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:bruno/bruno.dart';
// import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
// import 'package:image_pickers/image_pickers.dart';

class PubLishedDailyOtherPage extends StatefulWidget {
  const PubLishedDailyOtherPage({Key? key}) : super(key: key);

  @override
  State<PubLishedDailyOtherPage> createState() =>
      _PubLishedDailyOtherPageState();
}

class _PubLishedDailyOtherPageState extends State<PubLishedDailyOtherPage> {

  // 用户输入的文件名
  String? key;

  // 用户输入的 partSize
  int partSize = 4;

  // 用户输入的 token
  String? token;

  String? qiniu_image_path;

  /// storage 实例

  /// 当前选择的文件
  // PlatformFile? selectedFile;

  TextEditingController _editingController = TextEditingController();

  /// 控制表情隐藏还是显示
  bool isShowEmoji = false;
  bool isShowImage = false;

  _emoJiList() {
    return FutureBuilder(
        future:
            DefaultAssetBundle.of(context).loadString("images/emoji_list.json"),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<dynamic> data = json.decode(snapshot.data.toString());

            return Stack(
              children: <Widget>[
                Container(
                  height: 200,
                  padding:
                      EdgeInsets.only(left: 0, top: 0, right: 0, bottom: 5),
                  color: AppColor.bgColor,
                  child: GridView.custom(
                    padding: EdgeInsets.all(0),
                    shrinkWrap: true,
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 6,
                      mainAxisSpacing: 0.5,
                      crossAxisSpacing: 6.0,
                    ),
                    childrenDelegate: SliverChildBuilderDelegate(
                      (context, index) {
                        return GestureDetector(
                          onTap: () {
                            _editingController.text = _editingController.text +
                                String.fromCharCode(data[index]["unicode"]);
                            setState(() {});
                          },
                          child: Center(
                            child: Text(
                              String.fromCharCode(data[index]["unicode"]),
                              style: TextStyle(fontSize: 15),
                            ),
                          ),
                        );
                      },
                      childCount: data.length,
                    ),
                  ),
                ),
              ],
            );
          }
          return const CupertinoActivityIndicator();
        });
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  // Future<void> openSelectFileWindow() async {
  //   final fileResult =
  //       await FilePicker.platform.pickFiles(allowMultiple: false);
  //   if (fileResult != null) {
  //     PlatformFile file = fileResult.files.first;
  //     print('选中文件: ${file.path}');
  //     // ignore: unnecessary_null_comparison
  //     if (file.size != null) {
  //       // 一般在非 web 平台上可以直接读取 size 属性
  //       print('文件尺寸：${humanizeFileSize(file.size.toDouble())}');
  //     } else if (file.bytes != null) {
  //       print('文件尺寸：${humanizeFileSize(file.bytes!.length.toDouble())}');
  //     }
  //
  //     setState(() {
  //       print('设置 selectedFile');
  //       selectedFile = file;
  //       startUpload();
  //     });
  //   }
  // }

  // void startUpload() {
  //   print('创建 PutController');
  //   putController = PutController();
  //
  //   var usedToken = token;
  //
  //   if (usedToken == null || usedToken == '') {
  //     print('token 不能为空');
  //     return;
  //   }
  //
  //   print('------------------------');
  //
  //   if (selectedFile == null) {
  //     print('请选择文件');
  //     return;
  //   }
  //
  //   print('开始上传文件');
  //
  //   final putOptions = PutOptions(
  //     key: key,
  //     partSize: partSize,
  //     controller: putController,
  //   );
  //   Future<PutResponse> upload;
  //   if (kIsWeb) {
  //     upload = storage.putBytes(
  //       selectedFile!.bytes!,
  //       usedToken,
  //       options: putOptions,
  //     );
  //   } else {
  //     upload = storage.putFile(
  //       File(selectedFile!.path!),
  //       usedToken,
  //       options: putOptions,
  //     );
  //   }
  //
  //   upload
  //     ..then((PutResponse response) {
  //       Map<String, dynamic> rawData = response.rawData;
  //       String hamstring = rawData["hash"];
  //       isShowImage = true;
  //
  //       print('$qiniu_image_path');
  //       setState(() {
  //
  //       });
  //
  //       setState(() {
  //         qiniu_image_path = _client.imageUrl + hamstring;
  //         print('$qiniu_image_path');
  //         print('------------------------');
  //       });
  //
  //     })
  //     ..catchError((dynamic error) {
  //       if (error is StorageError) {
  //         switch (error.type) {
  //           case StorageErrorType.CONNECT_TIMEOUT:
  //             print('发生错误: 连接超时');
  //             break;
  //           case StorageErrorType.SEND_TIMEOUT:
  //             print('发生错误: 发送数据超时');
  //             break;
  //           case StorageErrorType.RECEIVE_TIMEOUT:
  //             print('发生错误: 响应数据超时');
  //             break;
  //           case StorageErrorType.RESPONSE:
  //             print('发生错误: ${error.message}');
  //             break;
  //           case StorageErrorType.CANCEL:
  //             print('发生错误: 请求取消');
  //             break;
  //           case StorageErrorType.UNKNOWN:
  //             print('发生错误: 未知错误');
  //             break;
  //           case StorageErrorType.NO_AVAILABLE_HOST:
  //             print('发生错误: 无可用 Host');
  //             break;
  //           case StorageErrorType.IN_PROGRESS:
  //             print('发生错误: 已在队列中');
  //             break;
  //         }
  //       } else {
  //         print('发生错误: ${error.toString()}');
  //       }
  //
  //       print('------------------------');
  //     });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false, // 就是这里
      backgroundColor: AppColor.bgColor,
      appBar: AppBar(
        backgroundColor: AppColor.themeColor,
        leading: IconButton(
          onPressed: () {
            Get.back();
          },
          icon: Image.asset(
            'images/leftarr.png',
            color: Colors.white,
            width: 15,
            height: 15,
          ),
        ),
        title: Text('发布项目'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              children: [
                BrnInputText(
                  maxHeight: 200,
                  minHeight: 30,
                  minLines: 1,
                  maxLength: 500,
                  bgColor: Colors.white,
                  textInputAction: TextInputAction.newline,
                  maxHintLines: 20,
                  textEditingController: _editingController,
                  hint: '记录一下您今天的工作成果何心得吧',
                  padding: EdgeInsets.fromLTRB(20, 10, 20, 14),
                  onTextChange: (text) {},
                  onSubmit: (text) {
                    print(text);
                  },
                ),
                SizedBox(
                  height: 1,
                ),
                Container(
                  padding: EdgeInsets.only(left: 15, top: 10),
                  height: 40,
                  color: Colors.white,
                  child: Container(
                    width: 200,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        GestureDetector(
                          onTap: () {
                            // openSelectFileWindow();
                          },
                          child: Image.asset(
                            'images/fujian_icon.png',
                            width: 15,
                            height: 15,
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          onTap: () {
                            isShowEmoji = !isShowEmoji;
                            print(isShowEmoji);
                            setState(() {});
                          },
                          child: Image.asset(
                            'images/biaoqing_icon.png',
                            width: 15,
                            height: 15,
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          onTap: () {},
                          child: Image.asset(
                            'images/aite_icon.png',
                            width: 15,
                            height: 15,
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          onTap: () {
                            // openSelectFileWindow();
                          },
                          child: Image.asset(
                            'images/tupian_icon.png',
                            width: 15,
                            height: 15,
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                      ],
                    ),
                  ),
                ),
                isShowEmoji == false ? Container() : _emoJiList(),

                isShowImage == false
                    ? Container()
                    : Container(
                        color: Colors.white,
                        margin: EdgeInsets.all(15),
                        child: Image.network(
                          qiniu_image_path!,
                          fit: BoxFit.cover,
                        ),
                      )
              ],
            ),
          ),
          // Expanded(child: BottomEnterPage()),
          BottomEnterPage(() {
            if (_editingController.text.isEmpty) {
              BotToast.showText(text: '内容不能为空,请填写内容');
              return;
            }
            print('点击了发布');
          }),
        ],
      ),
    );
  }
}
